﻿using System;
using System.Windows.Forms;
using DbManager;
using DbManager.DataManager;
using DbManager.QueryBuilder;
using DbManager.QueryBuilder.DbEntity.IND;
using DbManager.QueryBuilder.DbEntity.IND.BazaOtdiha;
using DbManager.QueryBuilder.DbEntity.IND.Gorod;
using DbManager.QueryBuilder.DbEntity.IND.Napravlenie;

namespace TAProject.UI.Service.Tour
{
    public partial class FormManageTour : FormTemplate
    {
        private readonly IConnectionManager _connectionManager;
        private readonly IDataManager _dataManager;
        private readonly AEntityBazaOtdiha _aEntityBazaOtdiha;
        private readonly AEntityGorod _aEntityGorod;
        private readonly AEntityNapravlenie _aEntityNapravlenie;
        private readonly Form _parentForm;

        private Type _activeType;

        public FormManageTour(Form parentForm, IDataManager dataManager, IConnectionManager connectionManager)
            : base(parentForm)
        {
            InitializeComponent();

            _parentForm = parentForm;
            _dataManager = dataManager;
            _connectionManager = connectionManager;

            _parentForm.Enabled = false;

            _aEntityNapravlenie = new EntityNapravlenie();
            _aEntityGorod = new EntityGorodByNapravlenie();
            _aEntityBazaOtdiha = new EntityBazaOtdihaByGorod();

            FillListBox(_aEntityNapravlenie, listBoxNapravlenie);
            FillDataGrid(_aEntityNapravlenie);
        }

        private void FormClose()
        {
            _parentForm.Enabled = true;
            Close();
        }

        private void ButtonCancelClick(object sender, EventArgs e)
        {
            FormClose();
        }

        private void FillListBox(IQuery iQuery, ListControl listBox)
        {
            if (iQuery.GetType() == typeof (EntityNapravlenie))
            {
                listBoxGorod.Enabled = false;
                listBoxBazaOtdiha.Enabled = false;
            }
            else if (iQuery.GetType() == typeof (EntityGorodByNapravlenie))
            {
                listBoxBazaOtdiha.Enabled = false;
            }

            try
            {
                var dataTable = _dataManager.GetDataTable(iQuery.GetSelectQuery(),
                                                          _connectionManager.GetConnection());
                if (dataTable == null) return;
                listBox.DataSource = dataTable;
                listBox.ValueMember = "Идентификатор";
                listBox.DisplayMember = "Название";
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void FillDataGrid(IQuery iQuery)
        {
            if (iQuery.GetType() == typeof (EntityNapravlenie))
            {
                labelStatusChange.Text = "Направление";
            }
            else if (iQuery.GetType() == typeof (EntityGorodByNapravlenie))
            {
                labelStatusChange.Text = "Город";
            }
            else if (iQuery.GetType() == typeof (EntityBazaOtdihaByGorod))
            {
                labelStatusChange.Text = "База отдыха";
            }

            _activeType = iQuery.GetType();

            try
            {
                var dataTable = _dataManager.GetDataTable(iQuery.GetSelectQuery(),
                                                          _connectionManager.GetConnection());
                if (dataTable == null) return;
                dataGridView.DataSource = dataTable.DefaultView;

                for (var i = 0; i < dataGridView.Columns.Count; i++)
                {
                    if (dataGridView.Columns[i].HeaderText.Contains("Идентификатор"))
                    {
                        dataGridView.Columns[i].Visible = false;
                    }
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void ListBoxNapravlenieSelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                var selectedValue = (int)listBoxNapravlenie.SelectedValue;
                if (selectedValue == 0)
                {
                    MessageBox.Show("Ошибка выбора направления.");
                }
                else
                {
                    _aEntityGorod.IDNapravlenie = selectedValue;
                    FillListBox(_aEntityGorod, listBoxGorod);
                    FillDataGrid(_aEntityGorod);
                }
            }
            catch (Exception)
            {
                return;
            }

            ManageEnabled();
        }

        private void ListBoxGorodSelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                var selectedValue = (int)listBoxGorod.SelectedValue;
                if (selectedValue == 0)
                {
                    MessageBox.Show("Ошибка выбора направления.");
                }
                else
                {
                    _aEntityBazaOtdiha.IDGorod = selectedValue;
                    FillListBox(_aEntityBazaOtdiha, listBoxBazaOtdiha);
                    FillDataGrid(_aEntityBazaOtdiha);
                }
            }
            catch (Exception)
            {
                return;
            }

            ManageEnabled();
        }

        private void ButtonEditNapravlenieClick(object sender, EventArgs e)
        {
            FillDataGrid(_aEntityNapravlenie);
            listBoxGorod.Enabled = false;
            listBoxBazaOtdiha.Enabled = false;
        }

        private void ButtonAddClick(object sender, EventArgs e)
        {
            //MessageBox.Show(_activeType.ToString());
            if (_activeType == typeof (EntityNapravlenie))
            {
                AddToDb(_aEntityNapravlenie, listBoxNapravlenie);
            }
            else if (_activeType == typeof (EntityGorodByNapravlenie))
            {
                AddToDb(_aEntityGorod, listBoxGorod);
            }
            else if (_activeType == typeof (EntityBazaOtdihaByGorod))
            {
                AddToDb(_aEntityBazaOtdiha, listBoxBazaOtdiha);
            }
        }

        private void ButtonDeleteClick(object sender, EventArgs e)
        {
            if (dataGridView.CurrentRow == null) return;
            if (_activeType == typeof(EntityNapravlenie))
            {
                DeleteFromDb(_aEntityNapravlenie, listBoxNapravlenie);
            }
            else if (_activeType == typeof (EntityGorodByNapravlenie))
            {
                DeleteFromDb(_aEntityGorod, listBoxGorod);
            }
            else if (_activeType == typeof(EntityBazaOtdihaByGorod))
            {
                DeleteFromDb(_aEntityBazaOtdiha, listBoxBazaOtdiha);
            }
        }

        private void ButtonEditClick(object sender, EventArgs e)
        {
            if (_activeType == typeof(EntityNapravlenie))
            {
                EditItemInDb(_aEntityNapravlenie, listBoxNapravlenie);
            }
            else if (_activeType == typeof (EntityGorodByNapravlenie))
            {
                EditItemInDb(_aEntityGorod, listBoxGorod);
            }
            else if (_activeType == typeof(EntityBazaOtdihaByGorod))
            {
                EditItemInDb(_aEntityBazaOtdiha, listBoxBazaOtdiha);
            }
        }

        private void EditItemInDb(IQueryInd iQueryInd, ListControl listControl)
        {
            if (dataGridView.CurrentRow == null) return;
            try
            {
                iQueryInd.ID =
                    (int) dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Идентификатор"].Value;
                iQueryInd.Name =
                    dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Название"].Value.ToString();
                Form form;
                if (iQueryInd.GetType() == typeof(EntityBazaOtdihaByGorod))
                {
                    iQueryInd.Description =
                        dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Описание"].Value.ToString();
                    form = new FormNameDescription(this, _dataManager, _connectionManager, iQueryInd, true);
                }
                else
                {
                    form = new FormName(this, _dataManager, _connectionManager, iQueryInd, true);
                }
                RunForm(form);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }


            FillListBox(iQueryInd, listControl);
            FillDataGrid(iQueryInd);
        }

        private void RunForm(Form form)
        {
            try
            {
                form.ShowDialog(this);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                Enabled = true;
            }
        }

        private void DeleteFromDb(IQueryInd iQueryInd, ListControl listBox)
        {
            if (dataGridView.CurrentRow == null) return;
            iQueryInd.ID = (int)dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Идентификатор"].Value;

            var rowAffected = _dataManager.ManageDataInDb(iQueryInd.GetDeleteQuery(),
                                                          _connectionManager.GetConnection());
            if (rowAffected == 0)
            {
                MessageBox.Show("Ошибка удаления.");
            }
            else
            {
                FillListBox(iQueryInd, listBox);
                FillDataGrid(iQueryInd);
            }
        }

        private void AddToDb(IQueryInd iQuery, ListControl listBox)
        {
            Form form;
            if (iQuery.GetType() == typeof(EntityBazaOtdihaByGorod))
            {
                form = new FormNameDescription(this, _dataManager, _connectionManager, iQuery, false);
            }
            else
            {
                form = new FormName(this, _dataManager, _connectionManager, iQuery, false);
            }
            RunForm(form);
            FillListBox(iQuery, listBox);
            FillDataGrid(iQuery);
        }

        private void ManageEnabled()
        {
            if (_activeType == typeof (EntityGorodByNapravlenie))
            {
                listBoxGorod.Enabled = true;
                listBoxBazaOtdiha.Enabled = false;
            }
            else if (_activeType == typeof(EntityBazaOtdihaByGorod))
            {
                listBoxBazaOtdiha.Enabled = true;
            }
        }
    }
}